home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1996 February: Tool Chest / Apple Developer CD Series Tool Chest February 1996 (Apple Computer)(1996).iso / Tool Chest / Development Tools & Languages / Macintosh Common Lisp Related / Lisp FAQ 14Sept94 / 3.Common Pitfalls < prev    next >
Encoding:
Internet Message Format  |  1994-09-15  |  35.5 KB  |  [TEXT/ttxt]

  1. Subject: FAQ: Lisp Frequently Asked Questions 3/7 [Monthly posting]
  2. Newsgroups: comp.lang.lisp,news.answers,comp.answers
  3. Summary: Common Pitfalls
  4. Distribution: world
  5. Followup-To: poster
  6. Reply-To: ai+lisp-faq@cs.cmu.edu
  7. Approved: news-answers-request@MIT.Edu
  8.  
  9. Archive-name: lisp-faq/part3
  10. Last-Modified: Tue Sep 13 18:05:47 1994 by Mark Kantrowitz
  11. Version: 1.50
  12. Maintainer: Mark Kantrowitz and Barry Margolin <ai+lisp-faq@cs.cmu.edu>
  13. URL: http://www.cs.cmu.edu:8001/Web/Groups/AI/html/faqs/lang/lisp/top.html
  14. Size: 36400 bytes, 797 lines
  15.  
  16. ;;; ****************************************************************
  17. ;;; Answers to Frequently Asked Questions about Lisp ***************
  18. ;;; ****************************************************************
  19. ;;; Written by Mark Kantrowitz and Barry Margolin
  20. ;;; lisp_3.faq
  21.  
  22. This post contains Part 3 of the Lisp FAQ.
  23.  
  24. If you think of questions that are appropriate for this FAQ, or would
  25. like to improve an answer, please send email to us at ai+lisp-faq@cs.cmu.edu.
  26.  
  27. This section contains a list of common pitfalls. Pitfalls are aspects
  28. of Common Lisp which are non-obvious to new programmers and often
  29. seasoned programmers as well.
  30.  
  31. Common Pitfalls (Part 3):
  32.  
  33.   [3-0]  Why does (READ-FROM-STRING "foobar" :START 3) return FOOBAR
  34.          instead of BAR?  
  35.   [3-1]  Why can't it deduce from (READ-FROM-STRING "foobar" :START 3)
  36.          that the intent is to specify the START keyword parameter
  37.          rather than the EOF-ERROR-P and EOF-VALUE optional parameters?   
  38.   [3-2]  Why can't I apply #'AND and #'OR?
  39.   [3-3]  I used a destructive function (e.g. DELETE, SORT), but it
  40.          didn't seem to work.  Why? 
  41.   [3-4]  After I NREVERSE a list, it's only one element long.  After I
  42.          SORT a list, it's missing things.  What happened? 
  43.   [3-5]  Why does (READ-LINE) return "" immediately instead of waiting
  44.          for me to type a line?  
  45.   [3-6]  I typed a form to the read-eval-print loop, but nothing happened. Why?
  46.   [3-7]  DEFMACRO doesn't seem to work.
  47.          When I compile my file, LISP warns me that my macros are undefined
  48.          functions, or complains "Attempt to call <function> which is 
  49.          defined as a macro.
  50.   [3-8]  Name conflict errors are driving me crazy! (EXPORT, packages)
  51.   [3-9]  Closures don't seem to work properly when referring to the
  52.          iteration variable in DOLIST, DOTIMES, DO and LOOP.
  53.   [3-10] What is the difference between FUNCALL and APPLY?
  54.   [3-11] Miscellaneous things to consider when debugging code.
  55.   [3-12] When is it right to use EVAL?
  56.   [3-13] Why does my program's behavior change each time I use it?
  57.   [3-14] When producing formatted output in Lisp, where should you put the
  58.          newlines (e.g., before or after the line, FRESH-LINE vs TERPRI,
  59.          ~& vs ~% in FORMAT)?
  60.   [3-15] I'm using DO to do some iteration, but it doesn't terminate. 
  61.   [3-16] My program works when interpreted but not when compiled!
  62.  
  63. Search for \[#\] to get to question number # quickly.
  64.  
  65. ----------------------------------------------------------------
  66. Subject: [3-0] Why does (READ-FROM-STRING "foobar" :START 3) return FOOBAR 
  67.                instead of BAR?
  68.  
  69. READ-FROM-STRING is one of the rare functions that takes both &OPTIONAL and
  70. &KEY arguments:
  71.  
  72.        READ-FROM-STRING string &OPTIONAL eof-error-p eof-value 
  73.                                &KEY :start :end :preserve-whitespace
  74.  
  75. When a function takes both types of arguments, all the optional
  76. arguments must be specified explicitly before any of the keyword
  77. arguments may be specified.  In the example above, :START becomes the
  78. value of the optional EOF-ERROR-P parameter and 3 is the value of the
  79. optional EOF-VALUE parameter.
  80.      
  81. To get the desired result, you should use
  82.    (READ-FROM-STRING "foobar" t nil :START 3)
  83. If you need to understand and use the optional arguments, please refer
  84. to CLTL2 under READ-FROM-STRING, otherwise, this will behave as
  85. desired for most purposes.
  86.  
  87. ----------------------------------------------------------------
  88. Subject: [3-1] Why can't it deduce from (READ-FROM-STRING "foobar" :START 3) 
  89.       that the intent is to specify the START keyword parameter rather than
  90.       the EOF-ERROR-P and EOF-VALUE optional parameters?
  91.  
  92. In Common Lisp, keyword symbols are first-class data objects.  Therefore,
  93. they are perfectly valid values for optional parameters to functions.
  94. There are only four functions in Common Lisp that have both optional and
  95. keyword parameters (they are PARSE-NAMESTRING, READ-FROM-STRING,
  96. WRITE-LINE, and WRITE-STRING), so it's probably not worth adding a
  97. nonorthogonal kludge to the language just to make these functions slightly
  98. less confusing; unfortunately, it's also not worth an incompatible change
  99. to the language to redefine those functions to use only keyword arguments.
  100.      
  101. ----------------------------------------------------------------
  102. Subject: [3-2] Why can't I apply #'AND and #'OR?
  103.  
  104. Here's the simple, but not necessarily satisfying, answer: AND and OR are
  105. macros, not functions; APPLY and FUNCALL can only be used to invoke
  106. functions, not macros and special operators.
  107.  
  108. OK, so what's the *real* reason?  The reason that AND and OR are macros
  109. rather than functions is because they implement control structure in
  110. addition to computing a boolean value.  They evaluate their subforms
  111. sequentially from left/top to right/bottom, and stop evaluating subforms as
  112. soon as the result can be determined (in the case of AND, as soon as a
  113. subform returns NIL; in the case of OR, as soon as one returns non-NIL);
  114. this is referred to as "short circuiting" in computer language parlance.
  115. APPLY and FUNCALL, however, are ordinary functions; therefore, their
  116. arguments are evaluated automatically, before they are called.  Thus, were
  117. APPLY able to be used with #'AND, the short-circuiting would be defeated.
  118.  
  119. Perhaps you don't really care about the short-circuiting, and simply want
  120. the functional, boolean interpretation.  While this may be a reasonable
  121. interpretation of trying to apply AND or OR, it doesn't generalize to other
  122. macros well, so there's no obvious way to have the Lisp system "do the
  123. right thing" when trying to apply macros.  The only function associated
  124. with a macro is its expander function; this function accepts and returns
  125. and form, so it cannot be used to compute the value.
  126.  
  127. The Common Lisp functions EVERY and SOME can be used to get the
  128. functionality you intend when trying to apply #'AND and #'OR.  For
  129. instance, the erroneous form:
  130.  
  131.    (apply #'and *list*)
  132.  
  133. can be translated to the correct form:
  134.  
  135.    (every #'identity *list*)
  136.  
  137. ----------------------------------------------------------------
  138. Subject: [3-3] I used a destructive function (e.g. DELETE, SORT), but 
  139.                it didn't seem to work.  Why?
  140.  
  141. I assume you mean that it didn't seem to modify the original list.  There
  142. are several possible reasons for this.  First, many destructive functions
  143. are not *required* to modify their input argument, merely *allowed* to; in
  144. some cases, the implementation may determine that it is more efficient to
  145. construct a new result than to modify the original (this may happen in Lisp
  146. systems that use "CDR coding", where RPLACD may have to turn a CDR-NEXT or
  147. CDR-NIL cell into a CDR-NORMAL cell), or the implementor may simply not
  148. have gotten around to implementing the destructive version in a truly
  149. destructive manner.  Another possibility is that the nature of the change
  150. that was made involves removing elements from the front of a list; in this
  151. case, the function can simply return the appropriate tail of the list,
  152. without actually modifying the list. And example of this is:
  153.      
  154.    (setq *a* (list 3 2 1))
  155.    (delete 3 *a*) => (2 1)
  156.    *a* => (3 2 1)
  157.  
  158. Similarly, when one sorts a list, SORT may destructively rearrange the
  159. pointers (cons cells) that make up the list. SORT then returns the cons
  160. cell that now heads the list; the original cons cell could be anywhere in
  161. the list. The value of any variable that contained the original head of the
  162. list hasn't changed, but the contents of that cons cell have changed
  163. because SORT is a destructive function:
  164.  
  165.    (setq *a* (list 2 1 3))
  166.    (sort *a* #'<) => (1 2 3)
  167.    *a* => (2 3)     
  168.  
  169. In both cases, the remedy is the same: store the result of the
  170. function back into the place whence the original value came, e.g.
  171.  
  172.    (setq *a* (delete 3 *a*))
  173.    *a* => (2 1)
  174.  
  175. Why don't the destructive functions do this automatically?  Recall
  176. that they are just ordinary functions, and all Lisp functions are
  177. called by value. They see the value of the argument, not the argument
  178. itself. Therefore, these functions do not know where the lists they
  179. are given came from; they are simply passed the cons cell that
  180. represents the head of the list. Their only obligation is to return
  181. the new cons cell that represents the head of the list. Thus
  182. "destructive" just means that the function may munge the list by
  183. modifying the pointers in the cars and cdrs of the list's cons cells.
  184. This can be more efficient, if one doesn't care whether the original
  185. list gets trashed or not.
  186.  
  187. One thing to be careful about when doing this (storing the result back
  188. into the original location) is that the original list might be
  189. referenced from multiple places, and all of these places may need to
  190. be updated.  For instance:
  191.  
  192.    (setq *a* (list 3 2 1))
  193.    (setq *b* *a*)
  194.    (setq *a* (delete 3 *a*))
  195.    *a* => (2 1)
  196.    *b* => (3 2 1) ; *B* doesn't "see" the change
  197.    (setq *a* (delete 1 *a*))
  198.    *a* => (2)
  199.    *b* => (3 2) ; *B* sees the change this time, though
  200.  
  201. One may argue that destructive functions could do what you expect by
  202. rearranging the CARs of the list, shifting things up if the first element
  203. is being deleted, as they are likely to do if the argument is a vector
  204. rather than a list.  In many cases they could do this, although it would
  205. clearly be slower.  However, there is one case where this is not possible:
  206. when the argument or value is NIL, and the value or argument, respectively,
  207. is not.  It's not possible to transform the object referenced from the
  208. original cell from one data type to another, so the result must be stored
  209. back.  Here are some examples:
  210.  
  211.    (setq *a* (list 3 2 1))
  212.    (delete-if #'numberp *a) => NIL
  213.    *a* => (3 2 1)
  214.    (setq *a* nil *b* '(1 2 3))
  215.    (nconc *a* *b*) => (1 2 3)
  216.    *a* => NIL
  217.  
  218. The names of most destructure functions (except for sort, delete,
  219. rplaca, rplacd, and setf of accessor functions) have the prefix N.
  220.  
  221. In summary, the two common problems to watch out for when using
  222. destructive functions are:
  223.  
  224.    1. Forgetting to store the result back. Even though the list
  225.       is modified in place, it is still necessary to store the
  226.       result of the function back into the original location, e.g.,
  227.            (setq foo (delete 'x foo))
  228.  
  229.       If the original list was stored in multiple places, you may
  230.       need to store it back in all of them, e.g.
  231.            (setq bar foo)
  232.            ...
  233.            (setq foo (delete 'x foo))
  234.            (setq bar foo)
  235.  
  236.    2. Sharing structure that gets modified. If it is important
  237.       to preserve the shared structure, then you should either
  238.       use a nondestructive operation or copy the structure first
  239.       using COPY-LIST or COPY-TREE.
  240.            (setq bar (cdr foo))
  241.            ...
  242.            (setq foo (sort foo #'<))
  243.            ;;; now it's not safe to use BAR
  244.  
  245. Note that even nondestructive functions, such as REMOVE, and UNION,
  246. can return a result which shares structure with an argument. 
  247. Nondestructive functions don't necessarily copy their arguments; they
  248. just don't modify them.
  249.      
  250. ----------------------------------------------------------------
  251. Subject: [3-4] After I NREVERSE a list, it's only one element long.  
  252.                After I SORT a list, it's missing things.  What happened?
  253.  
  254. These are particular cases of the previous question.  Many NREVERSE and
  255. SORT implementations operate by rechaining all the CDR links in the list's
  256. backbone, rather than by replacing the CARs.  In the case of NREVERSE, this
  257. means that the cons cell that was originally first in the list becomes the
  258. last one.  As in the last question, the solution is to store the result
  259. back into the original location.
  260.      
  261. ----------------------------------------------------------------
  262. Subject: [3-5] Why does (READ-LINE) return "" immediately instead of 
  263.                waiting for me to type a line?
  264.  
  265. Many Lisp implementations on line-buffered systems do not discard the
  266. newline that the user must type after the last right parenthesis in order
  267. for the line to be transmitted from the OS to Lisp.  Lisp's READ function
  268. returns immediately after seeing the matching ")" in the stream.  When
  269. READLINE is called, it sees the next character in the stream, which is a
  270. newline, so it returns an empty line.  If you were to type "(read-line)This
  271. is a test" the result would be "This is a test".
  272.  
  273. The simplest solution is to use (PROGN (CLEAR-INPUT) (READ-LINE)).  This
  274. discards the buffered newline before reading the input.  However, it would
  275. also discard any other buffered input, as in the "This is a test" example
  276. above; some implementation also flush the OS's input buffers, so typeahead
  277. might be thrown away.
  278.  
  279. ----------------------------------------------------------------
  280. Subject: [3-6] I typed a form to the read-eval-print loop, but 
  281.                nothing happened. Why?
  282.  
  283. There's not much to go on here, but a common reason is that you haven't
  284. actually typed a complete form.  You may have typed a doublequote, vertical
  285. bar, "#|" comment beginning, or left parenthesis that you never matched
  286. with another doublequote, vertical bar, "|#", or right parenthesis,
  287. respectively.  Try typing a few right parentheses followed by Return.
  288.  
  289. ----------------------------------------------------------------
  290. Subject: [3-7]  DEFMACRO doesn't seem to work. 
  291.                 When I compile my file, LISP warns me that my macros
  292.                 are undefined functions, or complains 
  293.                   "Attempt to call <function> which is defined as a macro."
  294.  
  295. When you evaluate a DEFMACRO form or proclaim a function INLINE, it
  296. doesn't go back and update code that was compiled under the old
  297. definition. When redefining a macro, be sure to recompile any
  298. functions that use the macro. Also be sure that the macros used in a
  299. file are defined before any forms in the same file that use them.
  300.  
  301. Certain forms, including LOAD, SET-MACRO-CHARACTER, and
  302. REQUIRE, are not normally evaluated at compile time. Common Lisp
  303. requires that macros defined in a file be used when compiling later
  304. forms in the file. If a Lisp doesn't follow the standard, it may be
  305. necessary to wrap an EVAL-WHEN form around the macro definition.
  306.  
  307. Most often the "macro was previously called as a function" problem
  308. occurs when files were compiled/loaded in the wrong order. For
  309. example, developers may add the definition to one file, but use it in
  310. a file which is compiled/loaded before the definition. To work around
  311. this problem, one can either fix the modularization of the system, or
  312. manually recompile the files containing the forward references to macros.
  313.  
  314. Also, if your macro calls functions at macroexpand time, those functions
  315. may need to be in an EVAL-WHEN. For example,
  316.  
  317.     (defun some-function (x)
  318.       x)
  319.  
  320.     (defmacro some-macro (y)
  321.       (let ((z (some-function y)))
  322.         `(print ',z)))
  323.  
  324. If the macros are defined in a file you require, make sure your
  325. require or load statement is in an appropriate EVAL-WHEN. Many people
  326. avoid all this nonsense by making sure to load all their files before
  327. compiling them, or use a system facility (or just a script file) that
  328. loads each file before compiling the next file in the system.
  329.  
  330. ----------------------------------------------------------------
  331. Subject: [3-8]  Name conflict errors are driving me crazy! (EXPORT, packages)
  332.  
  333. If a package tries to export a symbol that's already defined, it will
  334. report an error. You probably tried to use a function only to discover
  335. that you'd forgotten to load its file. The failed attempt at using the
  336. function caused its symbol to be interned. So now, when you try to
  337. load the file, you get a conflict. Unfortunately, understanding and
  338. correcting the code which caused the export problem doesn't make those
  339. nasty error messages go away. That symbol is still interned where it
  340. shouldn't be. Use unintern to remove the symbol from a package before
  341. reloading the file. Also, when giving arguments to REQUIRE or package
  342. functions, use strings or keywords, not symbols: (find-package "FOO"),
  343. (find-package :foo). 
  344.  
  345. A sometimes useful technique is to rename (or delete) a package
  346. that is "too messed up".  Then you can reload the relevant files
  347. into a "clean" package.
  348.  
  349. ----------------------------------------------------------------
  350. Subject: [3-9]  Closures don't seem to work properly when referring to the
  351.                 iteration variable in DOLIST, DOTIMES, DO and LOOP.
  352.  
  353. DOTIMES, DOLIST, DO and LOOP all use assignment instead of binding to
  354. update the value of the iteration variables. So something like
  355.    
  356.    (let ((l nil))
  357.      (dotimes (n 10)
  358.        (push #'(lambda () n)
  359.          l)))
  360.  
  361. will produce 10 closures over the same value of the variable N. To
  362. avoid this problem, you'll need to create a new binding after each
  363. assignment: 
  364.  
  365.    (let ((l nil))
  366.      (dotimes (n 10)
  367.     (let ((n n))
  368.       (push #'(lambda () n)
  369.         l))))
  370.  
  371. Then each closure will be over a new binding of n.
  372.  
  373. This is one reason why programmers who use closures prefer MAPC and
  374. MAPCAR to DOLIST.
  375.  
  376. ----------------------------------------------------------------
  377. Subject: [3-10] What is the difference between FUNCALL and APPLY?
  378.  
  379. FUNCALL is useful when the programmer knows the length of the argument
  380. list, but the function to call is either computed or provided as a
  381. parameter.  For instance, a simple implementation of MEMBER-IF (with
  382. none of the fancy options) could be written as:
  383.  
  384. (defun member-if (predicate list)
  385.   (do ((tail list (cdr tail)))
  386.       ((null tail))
  387.    (when (funcall predicate (car tail))
  388.      (return-from member-if tail))))
  389.  
  390. The programmer is invoking a caller-supplied function with a known
  391. argument list.
  392.  
  393. APPLY is needed when the argument list itself is supplied or computed.
  394. Its last argument must be a list, and the elements of this list become
  395. individual arguments to the function.  This frequently occurs when a
  396. function takes keyword options that will be passed on to some other
  397. function, perhaps with application-specific defaults inserted.  For
  398. instance:
  399.  
  400. (defun open-for-output (pathname &rest open-options)
  401.   (apply #'open pathname :direction :output open-options))
  402.  
  403. FUNCALL could actually have been defined using APPLY:
  404.  
  405. (defun funcall (function &rest arguments)
  406.   (apply function arguments))
  407.  
  408. ----------------------------------------------------------------
  409. Subject: [3-11] Miscellaneous things to consider when debugging code.
  410.  
  411. This question lists a variety of problems to watch out for when
  412. debugging code. This is sort of a catch-all question for problems too
  413. small to merit a question of their own. See also question [1-3] for
  414. some other common problems.
  415.  
  416. Functions:
  417.  
  418.   * (flet ((f ...)) (eq #'f #'f)) can return false.
  419.  
  420.   * The function LIST-LENGTH is not a faster, list-specific version
  421.     of the sequence function LENGTH.  It is list-specific, but it's
  422.     slower than LENGTH because it can handle circular lists.
  423.  
  424.   * Don't confuse the use of LISTP and CONSP. CONSP tests for the
  425.     presence of a cons cell, but will return NIL when called on NIL.
  426.     LISTP could be defined as (defun listp (x) (or (null x) (consp x))).
  427.  
  428.   * Use the right test for equality: 
  429.         EQ      tests if the objects are identical -- numbers with the
  430.                 same value need not be EQ, nor are two similar lists
  431.                 necessarily EQ. Similarly for characters and strings.
  432.                 For instance, (let ((x 1)) (eq x x)) is not guaranteed
  433.                 to return T.
  434.         EQL     Like EQ, but is also true if the arguments are numbers
  435.                 of the same type with the same value or character objects
  436.                 representing the same character. (eql -0.0 0.0) is not
  437.                 guaranteed to return T.
  438.         EQUAL   Tests if the arguments are structurally isomorphic, using
  439.                 EQUAL to compare components that are conses, bit-vectors, 
  440.                 strings or pathnames, and EQ for all other data objects
  441.                 (except for numbers and characters, which are compared
  442.                 using EQL). Except for strings and bit-vectors, arrays
  443.                 are EQUAL only if they are EQ.
  444.         EQUALP  Like EQUAL, but ignores type differences when comparing 
  445.                 numbers and case differences when comparing characters.
  446.         =       Compares the values of two numbers even if they are of
  447.                 different types.
  448.         CHAR=   Case-sensitive comparison of characters.
  449.         CHAR-EQUAL      Case-insensitive comparison of characters.
  450.         STRING= Compares two strings, checking if they are identical.
  451.                 It is case sensitive.
  452.         STRING-EQUAL  Like STRING=, but case-insensitive.
  453.  
  454.   * Some destructive functions that you think would modify CDRs might
  455.     modify CARs instead.  (E.g., NREVERSE.)
  456.  
  457.   * READ-FROM-STRING has some optional arguments before the
  458.     keyword parameters.  If you want to supply some keyword
  459.     arguments, you have to give all of the optional ones too.
  460.  
  461.   * If you use the function READ-FROM-STRING, you should probably bind
  462.     *READ-EVAL* to NIL. Otherwise an unscrupulous user could cause a
  463.     lot of damage by entering 
  464.         #.(shell "cd; rm -R *")
  465.     at a prompt.
  466.  
  467.   * Only functional objects can be funcalled in CLtL2, so a lambda
  468.     expression '(lambda (..) ..) is no longer suitable. Use
  469.     #'(lambda (..) ..) instead. If you must use '(lambda (..) ..),
  470.     coerce it to type FUNCTION first using COERCE.
  471.  
  472. Methods:
  473.  
  474.   * PRINT-OBJECT methods can make good code look buggy. If there is a
  475.     problem with the PRINT-OBJECT methods for one of your classes, it
  476.     could make it seem as though there were a problem with the object.
  477.     It can be very annoying to go chasing through your code looking for
  478.     the cause of the wrong value, when the culprit is just a bad
  479.     PRINT-OBJECT method.
  480.  
  481. Initialization:
  482.  
  483.   * Don't count on array elements being initialized to NIL, if you don't
  484.     specify an :initial-element argument to MAKE-ARRAY. For example,
  485.          (make-array 10) => #(0 0 0 0 0 0 0 0 0 0)
  486.  
  487. Iteration vs closures:
  488.  
  489.   * DO and DO* update the iteration variables by assignment; DOLIST and
  490.     DOTIMES are allowed to use assignment (rather than a new binding).
  491.     (All CLtL1 says of DOLIST and DOTIMES is that the variable "is
  492.     bound" which has been taken as _not_ implying that there will be
  493.     separate bindings for each iteration.) 
  494.  
  495.     Consequently, if you make closures over an iteration variable
  496.     in separate iterations they may nonetheless be closures over
  497.     the same variable and hence will all refer to the same value
  498.     -- whatever value the variable was given last.  For example,
  499.         (let ((fns '()))
  500.           (do ((x '(1 2) (cdr x)))
  501.               ((null x))
  502.             (push #'(lambda () x)
  503.                   fns))
  504.           (mapcar #'funcall (reverse fns)))
  505.     returns (nil nil), not (1 2), not even (2 2). Thus 
  506.          (let ((l nil)) 
  507.            (dolist (a '(1 2 3) l) 
  508.              (push #'(lambda () a)
  509.                    l)))
  510.     returns a list of three closures closed over the same bindings, whereas
  511.          (mapcar #'(lambda (a) #'(lambda () a)) '(1 2 3))
  512.     returns a list of closures over distinct bindings.
  513.  
  514. Defining Variables and Constants:
  515.  
  516.   * (defvar var init) assigns to the variable only if it does not
  517.     already have a value.  So if you edit a DEFVAR in a file and
  518.     reload the file only to find that the value has not changed,
  519.     this is the reason.  (Use DEFPARAMETER if you want the value
  520.     to change upon reloading.) DEFVAR is used to declare a variable
  521.     that is changed by the program; DEFPARAMETER is used to declare
  522.     a variable that is normally constant, but which can be changed
  523.     to change the functioning of a program.
  524.  
  525.   * DEFCONSTANT has several potentially unexpected properties:
  526.  
  527.      - Once a name has been declared constant, it cannot be used a
  528.        the name of a local variable (lexical or special) or function
  529.        parameter.  Really.  See page 87 of CLtL2.
  530.  
  531.      - A DEFCONSTANT cannot be re-evaluated (eg, by reloading the
  532.        file in which it appears) unless the new value is EQL to the
  533.        old one.  Strictly speaking, even that may not be allowed.
  534.        (DEFCONSTANT is "like DEFPARAMETER" and hence does an
  535.        assignment, which is not allowed if the name has already
  536.        been declared constant by DEFCONSTANT.)
  537.  
  538.        Note that this makes it difficult to use anything other
  539.        than numbers, symbols, and characters as constants.       
  540.  
  541.      - When compiling (DEFCONSTANT name form) in a file, the form
  542.        may be evaluated at compile-time, load-time, or both.  
  543.  
  544.        (You might think it would be evaluated at compile-time and
  545.        the _value_ used to obtain the object at load-time, but it
  546.        doesn't have to work that way.)
  547.  
  548. Declarations:
  549.  
  550.   * You often have to declare the result type to get the most
  551.     efficient arithmetic.  Eg, 
  552.  
  553.        (the fixnum (+ (the fixnum e1) (the fixnum e2)))
  554.  
  555.      rather than
  556.  
  557.        (+ (the fixnum e1) (the fixnum e2))
  558.  
  559.   * Declaring the iteration variable of a DOTIMES to have type FIXNUM
  560.     does not guarantee that fixnum arithmetic will be used.  That is,
  561.     implementations that use fixnum-specific arithmetic in the presence
  562.     of appropriate declaration may not think _this_ declaration is
  563.     sufficient.  It may help to declare that the limit is also a
  564.     fixnum, or you may have to write out the loop as a DO and add
  565.     appropriate declarations for each operation involved.
  566.  
  567. FORMAT related errors:
  568.  
  569.   * When printing messages about files, filenames like foo~ (a GNU-Emacs
  570.     backup file) may cause problems with poorly coded FORMAT control
  571.     strings.
  572.  
  573.   * Beware of using an ordinary string as the format string,
  574.     i.e., (format t string), rather than (format t "~A" string).
  575.  
  576.   * FORMAT returns NIL, so if you added a format statement at the end
  577.     of a function for debugging purposes, and that function normally
  578.     returns a value to the caller, you may have changed the behavior
  579.     of your program.
  580.  
  581. Miscellaneous:
  582.  
  583.   * Be careful of circular lists and shared list structure. 
  584.  
  585.   * Watch out for macro redefinitions.
  586.  
  587.   * A NOTINLINE may be needed if you want SETF of SYMBOL-FUNCTION to
  588.     affect calls within a file.  (See CLtL2, page 686.)
  589.  
  590.   * When dividing two numbers, beware of creating a rational number where
  591.     you intended to get an integer or floating point number. Use TRUNCATE
  592.     or ROUND to get an integer and FLOAT to ensure a floating point
  593.     number. This is a major source of errors when porting ZetaLisp or C
  594.     code to Common Lisp.
  595.  
  596.   * If your code doesn't work because all the symbols are mysteriously
  597.     in the keyword package, one of your comments has a colon (:) in
  598.     it instead of a semicolon (;).
  599.  
  600.   * If you redefine a function while in the debugger, the redefinition
  601.     may not take effect immediately. This will happen, for example,
  602.     when the execution stack is halted near the invocation of the function.
  603.     The function pointer on the stack will still be pointing to the
  604.     old definition. Go up the stack a few levels before restarting to
  605.     avoid reusing the old definition.
  606.  
  607. ----------------------------------------------------------------
  608. Subject: [3-12] When is it right to use EVAL?
  609.  
  610. Hardly ever.  Any time you think you need to use EVAL, think hard about it.
  611. EVAL is useful when implementing a facility that provides an external
  612. interface to the Lisp interpreter.  For instance, many Lisp-based editors
  613. provide a command that prompts for a form and displays its value.
  614. Inexperienced macro writers often assume that they must explicitly EVAL the
  615. subforms that are supposed to be evaluated, but this is not so; the correct
  616. way to write such a macro is to have it expand into another form that has
  617. these subforms in places that will be evaluated by the normal evaluation
  618. rules.  Explicit use of EVAL in a macro is likely to result in one of two
  619. problems: the dreaded "double evaluation" problem, which may not show up
  620. during testing if the values of the expressions are self-evaluating
  621. constants (such as numbers); or evaluation at compile time rather than
  622. runtime.  For instance, if Lisp didn't have IF and one desired to write it,
  623. the following would be wrong:
  624.  
  625.    (defmacro if (test then-form &optional else-form)
  626.      ;; this evaluates all the subforms at compile time, and at runtime
  627.      ;; evaluates the results again.
  628.      `(cond (,(eval test) ,(eval then-form))
  629.             (t ,(eval else-form))))
  630.  
  631.    (defmacro if (test then-form &optional else-form)
  632.      ;; this double-evaluates at run time
  633.      `(cond ((eval ,test) (eval ,then-form))
  634.             (t (eval ,else-form)))
  635.  
  636. This is correct:
  637.  
  638.    (defmacro if (test then-form &optional else-form)
  639.      `(cond (,test ,then-form)
  640.             (t ,else-form)))
  641.  
  642. The following question (taken from an actual post) is typical of the
  643. kind of question asked by a programmer who is misusing EVAL:
  644.  
  645.    I would like to be able to quote all the atoms except the first in a
  646.    list of atoms.  The purpose is to allow a function to be read in and
  647.    evaluated as if its arguments had been quoted.
  648.  
  649. This is the wrong approach to solving the problem. Instead, he should
  650. APPLY the CAR of the form to the CDR of the form. Then quoting the
  651. rest of the form is unnecessary. But one wonders why he's trying to
  652. solve this problem in the first place, since the toplevel REP loop
  653. already involves a call to EVAL. One gets the feeling that if we knew
  654. more about what he's trying to accomplish, we'd be able to point out a
  655. more appropriate solution that uses neither EVAL nor APPLY.
  656.  
  657. On the other hand, EVAL can sometimes be necessary when the only portable
  658. interface to an operation is a macro. 
  659.  
  660. ----------------------------------------------------------------
  661. Subject: [3-13] Why does my program's behavior change each time I use it?
  662.  
  663. Most likely your program is altering itself, and the most common way this
  664. may happen is by performing destructive operations on embedded constant
  665. data structures.  For instance, consider the following:
  666.  
  667.    (defun one-to-ten-except (n)
  668.      (delete n '(1 2 3 4 5 6 7 8 9 10)))
  669.    (one-to-ten-except 3) => (1 2 4 5 6 7 8 9 10)
  670.    (one-to-ten-except 5) => (1 2 4 6 7 8 9 10) ; 3 is missing
  671.  
  672. The basic problem is that QUOTE returns its argument, *not* a copy of
  673. it. The list is actually a part of the lambda expression that is in
  674. ONE-TO-TEN-EXCEPT's function cell, and any modifications to it (e.g., by
  675. DELETE) are modifications to the actual object in the function definition.
  676. The next time that the function is called, this modified list is used.
  677.  
  678. In some implementations calling ONE-TO-TEN-EXCEPT may even result in
  679. the signalling of an error or the complete aborting of the Lisp process.  Some
  680. Lisp implementations put self-evaluating and quoted constants onto memory
  681. pages that are marked read-only, in order to catch bugs such as this.
  682. Details of this behavior may vary even within an implementation,
  683. depending on whether the code is interpreted or compiled (perhaps due to
  684. inlined DEFCONSTANT objects or constant folding optimizations).
  685.  
  686. All of these behaviors are allowed by the draft ANSI Common Lisp
  687. specification, which specifically states that the consequences of modifying
  688. a constant are undefined (X3J13 vote CONSTANT-MODIFICATION:DISALLOW).
  689.  
  690. To avoid these problems, use LIST to introduce a list, not QUOTE. QUOTE
  691. should be used only when the list is intended to be a constant which
  692. will not be modified.  If QUOTE is used to introduce a list which will
  693. later be modified, use COPY-LIST to provide a fresh copy.
  694.  
  695. For example, the following should all work correctly:
  696.  
  697.    o  (remove 4 (list 1 2 3 4 1 3 4 5))
  698.    o  (remove 4 '(1 2 3 4 1 3 4 5))   ;; Remove is non-destructive.
  699.    o  (delete 4 (list 1 2 3 4 1 3 4 5))
  700.    o  (let ((x (list 1 2 4 1 3 4 5)))
  701.         (delete 4 x))
  702.    o  (defvar *foo* '(1 2 3 4 1 3 4 5))
  703.       (delete 4 (copy-list *foo*))
  704.       (remove 4 *foo*)
  705.       (let ((x (copy-list *foo*)))
  706.          (delete 4 x))
  707.  
  708. The following, however, may not work as expected:
  709.  
  710.    o  (delete 4 '(1 2 3 4 1 3 4 5))
  711.  
  712. Note that similar issues may also apply to hard-coded strings. If you
  713. want to modify elements of a string, create the string with MAKE-STRING.
  714.  
  715. ----------------------------------------------------------------
  716. Subject: [3-14]  When producing formatted output in Lisp, where should you 
  717.         put the newlines (e.g., before or after the line, FRESH-LINE vs TERPRI,
  718.         ~& vs ~% in FORMAT)?
  719.  
  720.  
  721. Where possible, it is desirable to write functions that produce output
  722. as building blocks. In contrast with other languages, which either
  723. conservatively force a newline at various times or require the program
  724. to keep track of whether it needs to force a newline, the Lisp I/O
  725. system keeps track of whether the most recently printed character was
  726. a newline or not. The function FRESH-LINE outputs a newline only if
  727. the stream is not already at the beginning of a line.  TERPRI forces a
  728. newline irrespective of the current state of the stream. These
  729. correspond to the ~& and ~% FORMAT directives, respectively. (If the
  730. Lisp I/O system can't determine whether it's physically at the
  731. beginning of a line, it assumes that a newline is needed, just in case.)
  732.  
  733. Thus, if you want formatted output to be on a line of its own, start
  734. it with ~& and end it with ~%. (Some people will use a ~& also at the
  735. end, but this isn't necessary, since we know a priori that we're not
  736. at the beginning of a line. The only exception is when ~& follows a
  737. ~A, to prevent a double newline when the argument to the ~A is a
  738. formatted string with a newline at the end.) For example, the
  739. following routine prints the elements of a list, N elements per line,
  740. and then prints the total number of elements on a new line:
  741.  
  742.    (defun print-list (list &optional (elements-per-line 10))
  743.      (fresh-line)
  744.      (loop for i upfrom 1
  745.            for element in list do
  746.        (format t "~A ~:[~;~%~]" element (zerop (mod i elements-per-line))))
  747.      (format t "~&~D~%" (length list)))
  748.  
  749. ----------------------------------------------------------------
  750. Subject: [3-15] I'm using DO to do some iteration, but it doesn't terminate. 
  751.  
  752. Your code probably looks something like
  753.    (do ((sublist list (cdr list))
  754.         ..)
  755.        ((endp sublist)
  756.         ..)
  757.      ..)
  758. or maybe
  759.    (do ((index start (+ start 2))
  760.         ..)
  761.        ((= index end)
  762.         ..)
  763.      ..)
  764.  
  765. The problem is caused by the (cdr list) and the (+ start 2) in the
  766. first line. You're using the original list and start index instead of
  767. the working sublist or index. Change them to (cdr sublist) and 
  768. (+ index 2) and your code should start working.
  769.  
  770. ----------------------------------------------------------------
  771. Subject: [3-16] My program works when interpreted but not when compiled!
  772.  
  773. Look for problems with your macro definitions, such as a macro that is
  774. missing a quote. When compiled, this definition essentially becomes a
  775. constant. But when interpreted, the body of the macro is executed each
  776. time the macro is called.
  777.  
  778. For example, in Allegro CL the following code will behave differently
  779. when interpreted and compiled:
  780.   (defvar x 10)
  781.   (defmacro foo () (incf x))
  782.   (defun bar () (+ (foo) (foo)))
  783. Putting a quote before the (incf x) in the definition of foo fixes the
  784. problem. 
  785.  
  786. If you use (SETF (SYMBOL-FUNCTION 'foo) ...) to change the definition
  787. of a built-in Lisp function named FOO, be aware that this may not work
  788. correctly (i.e., as desired) in compiled code in all Lisps. In some
  789. Lisps, the compiler treats certain symbols in the LISP package
  790. specially, ignoring the function definition. If you want to redefine a
  791. standard function try proclaiming/declaring it NOTINLINE prior to
  792. compiling any use that should go through the function cell. (Note that
  793. this is not guarranteed to work, since X3J13 has stated that it is not
  794. permitted to redefine any of the standard functions).
  795.  
  796. ----------------------------------------------------------------
  797. ;;; *EOF*
  798.